package com.yzmoney.common.web.springmvc;

import com.yzmoney.common.util.JDKStackTrace;
import com.yzmoney.common.constant.Constants;
import com.yzmoney.common.constant.PropertyUtils;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.TemplateHashModel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by LiuJun on 2015/7/13.
 */
public class ExtSharedFreeMarkerView extends ExtFreeMarkerView {
    private static final Log log = LogFactory.getLog(ExtSharedFreeMarkerView.class);

    @Override
    protected void initServletContext(ServletContext servletContext) throws BeansException {
        super.initServletContext(servletContext);
        try {
            Configuration cfg = this.getConfiguration();
            BeansWrapper wrapper = (BeansWrapper) cfg.getObjectWrapper();
            TemplateHashModel staticModels = wrapper.getStaticModels();

            //测试静态类
            TemplateHashModel model = (TemplateHashModel) staticModels.get("com.yzmoney.common.util.Functions");
            this.getConfiguration().setSharedVariable("Functions", model);

          //格式化
            TemplateHashModel formatUtilModel = (TemplateHashModel) staticModels.get("com.yzmoney.common.util.FormatUtil");
            this.getConfiguration().setSharedVariable("FormatUtil", formatUtilModel);

        } catch (Exception ex) {
            log.warn(JDKStackTrace.getJDKStrack(ex));
        }
    }

    protected void exposeHelpers(Map model, HttpServletRequest request) throws Exception {
        super.exposeHelpers(model, request);
        model.put("serviceNumber", PropertyUtils.getValue(Constants.PROPERTY_KEY_SERVER_NUMBER, ""));
        model.put("serviceHotline", PropertyUtils.getValue(Constants.PROPERTY_KEY_SERVER_HOTLINE, ""));
        model.put("resUrl",PropertyUtils.getResourceRootUrl());
        model.put("resRoot",PropertyUtils.getResourceRootPath());
    }
}
